package com.zone.core.binding

import androidx.annotation.LayoutRes
import androidx.databinding.BindingAdapter
import androidx.paging.PagedList
import androidx.recyclerview.widget.RecyclerView
import com.zone.core.base.adapter.BasePageAdapter
import com.zone.core.base.adapter.SimplePageAdapter


/**
 * RecycleView设置数据，item的点击监听
 * 如果没适配器则加载SimpleBindingAdapter和布局
 */
@BindingAdapter("pageData", "pageItemLayout", "itemClick", "itemEventHandler")
fun <T> setPageData(
    recyclerView: RecyclerView,
    data: PagedList<T>?,
    @LayoutRes itemLayout: Int,
    listener: BasePageAdapter.OnItemClickListener<T>?,
    itemEventHandler: Any?
) {
    val adapter = recyclerView.adapter
    if (adapter == null) {
        val simplePageAdapter = SimplePageAdapter<T>(itemLayout)
        simplePageAdapter.submitList(data)
        simplePageAdapter.itemClickListener = listener
        simplePageAdapter.itemEventHandler = itemEventHandler
        recyclerView.adapter = simplePageAdapter
    } else if (adapter is SimplePageAdapter<*>) {
        (adapter as SimplePageAdapter<T>).submitList(data)
        adapter.itemClickListener = listener
        adapter.itemEventHandler = itemEventHandler
    }
}

/**
 * RecycleView设置数据，item的点击监听
 * 如果没适配器则加载SimpleBindingAdapter和布局
 */
@BindingAdapter("pageData", "pageItemLayout", "itemClick")
fun <T> setPageData(
    recyclerView: RecyclerView,
    data: PagedList<T>?,
    @LayoutRes itemLayout: Int,
    listener: BasePageAdapter.OnItemClickListener<T>?
) {
    setPageData(recyclerView, data, itemLayout, listener, null)
}

/**
 * RecycleView设置数据，item的点击监听
 * 如果没适配器则加载SimpleBindingAdapter和布局
 */
@BindingAdapter("pageData", "pageItemLayout", "itemEventHandler")
fun <T> setPageData(
    recyclerView: RecyclerView,
    data: PagedList<T>?,
    @LayoutRes itemLayout: Int,
    itemEventHandler: Any?
) {
    setPageData(recyclerView, data, itemLayout, null, itemEventHandler)
}

/**
 * RecycleView设置数据，item的点击监听
 * 如果没适配器则加载SimpleBindingAdapter和布局
 */
@BindingAdapter("pageData", "pageItemLayout")
fun <T> setPageData(
    recyclerView: RecyclerView,
    data: PagedList<T>?,
    @LayoutRes itemLayout: Int
) {
    setPageData(recyclerView, data, itemLayout, null, null)
}
